package com.core.website.api;

import cn.easyes.core.biz.PageInfo;
import com.core.website.common.Result;
import com.core.website.common.ResultUtil;
import com.core.website.common.TableDataInfo;
import com.core.website.entity.Approval;
import com.core.website.entity.Column;
import com.core.website.entity.Content;
import com.core.website.entity.User;
import com.core.website.mapper.ContentMapper;
import com.core.website.mapper.RoleMapper;
import com.core.website.service.ColumnService;
import com.core.website.service.ContentService;
import com.core.website.service.IpService;
import com.core.website.util.IpAddressUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
@RequestMapping("/contentApi")
public class ContentApi {

    @Autowired
    private ContentService contentService;
    @Autowired
    private ColumnService columnService;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private IpService ipService;
    @PostMapping("/add")
    public Result add(@RequestBody Content content){
        content.setArticleTitle(content.getTitle());
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null==subject){
            return ResultUtil.error(-1000,"用户未登录");
        }
        content.setCreateBy(subject.getId());
        if(StringUtils.isEmpty(content.getOrganization())){
            content.setOrganization(subject.getOrganizationId());
        }
        if(null==content.getCreateTime()){
            content.setCreateTime(new Date());
        }
        content.setSendNum(1);
        int result=contentService.add(content);
        return ResultUtil.success(result);
    }
    @PostMapping("/approval")
    public Result approval(@RequestBody Approval approval){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null==subject){
            return ResultUtil.error(-1,"请重新登录！");
        }
        String top = approval.getTop();
        String nice = approval.getNice();
        int result=contentService.approval(approval);
        contentService.top(approval.getContentId(),top);
        contentService.nice(approval.getContentId(),nice);
        return ResultUtil.success(result);
    }
    @PostMapping("/edit")
    public Result edit(@RequestBody Content content){
        content.setArticleTitle(content.getTitle());
        int result=contentService.edit(content);
        return ResultUtil.success(result);
    }
    @PostMapping("/delete")
    public Result delete(@RequestBody List<String> ids){
        int result=contentService.delete(ids);
        return ResultUtil.success(result);
    }
    @PostMapping("/queryAll")
    public Result queryAll(@RequestBody Content content,HttpServletRequest request){
        List<Content> result=contentService.queryAll(content);
        if(StringUtils.isNotEmpty(content.getColumnId())){
            Column column=columnService.queryOne(content.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    for(Content content1:result){
                        content1.setContentThumbs(false);
                        for(String ip:ipList){
                            int i=contentService.queryThumbs(ip,content1.getId());
                            if(i>0){
                                content1.setContentThumbs(true);
                                continue;
                            }
                        }
                    }
                }
            }

        }
        return ResultUtil.success(result);
    }
    @PostMapping("/globalQueryAll")
    public Result globalQueryAll(@RequestBody Content content){
        PageInfo<Content> result=contentService.globalQueryAll(content);
        return ResultUtil.success(result);
    }
    @PostMapping("/globalQueryAllContent")
    public Result globalQueryAllContent(@RequestBody Content content){
        PageInfo<Content> result=contentService.globalQueryAllContent(content);
        return ResultUtil.success(result);
    }
    @PostMapping("/queryCascadePage")
    public TableDataInfo queryCascadePage(@RequestBody Content content){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null!=subject){
            Set<String> list = roleMapper.queryRoleCodeByUserId(subject.getId());
            if(!list.contains("admin")){
                content.setCreateBy(subject.getId());
            }
        }
        PageHelper.startPage(content.getPageNum(), content.getPageSize());
        List<Content> result=contentService.queryCascadeAll(content);
        return TableDataInfo.getDataTable(result);
    }
    @PostMapping("/changeNo")
    public Result changeNo(@RequestBody Content content){
        int result=contentService.changeNo(content);
        return ResultUtil.success(result);
    }
    @PostMapping("/queryPage")
    public TableDataInfo queryPage(@RequestBody Content content,HttpServletRequest request){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null!=subject){
            Set<String> list = roleMapper.queryRoleCodeByUserId(subject.getId());
            if(!list.contains("admin")){
                content.setCreateBy(subject.getId());
            }
        }
        List<Content> result=contentService.queryAll(content);
        if(StringUtils.isNotEmpty(content.getColumnId())){
            Column column=columnService.queryOne(content.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    for(Content content1:result){
                        content1.setContentThumbs(false);
                        for(String ip:ipList){
                            int i=contentService.queryThumbs(ip,content1.getId());
                            if(i>0){
                                content1.setContentThumbs(true);
                                continue;
                            }
                        }
                    }
                }
            }

        }
        return TableDataInfo.getDataTable(result);
    }

    /**
     * 网页查询新闻 按照机构查询
     * @param content
     * @param request
     * @return
     */
    @PostMapping("/queryListByOrg")
    public Result queryListByOrg(@RequestBody Content content,HttpServletRequest request){
        List<Content> result=contentService.queryListByOrg(content);
        if(StringUtils.isNotEmpty(content.getColumnId())){
            Column column=columnService.queryOne(content.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    for(Content content1:result){
                        content1.setContentThumbs(false);
                        for(String ip:ipList){
                            int i=contentService.queryThumbs(ip,content1.getId());
                            if(i>0){
                                content1.setContentThumbs(true);
                                continue;
                            }
                        }
                    }
                }
            }

        }
        return ResultUtil.success(result);
    }
    @PostMapping("/queryApprovalPage")
    public TableDataInfo queryApprovalPage(@RequestBody Content content,HttpServletRequest request){
        User subject = (User) SecurityUtils.getSubject().getPrincipal();
        if(null!=subject){
            Set<String> list = roleMapper.queryRoleCodeByUserId(subject.getId());
            if(!list.contains("admin")){
                content.setCreateBy(subject.getId());
            }
        }
        List<Content> result=contentService.queryApprovalPage(content);
        if(StringUtils.isNotEmpty(content.getColumnId())){
            Column column=columnService.queryOne(content.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    for(Content content1:result){
                        content1.setContentThumbs(false);
                        for(String ip:ipList){
                            int i=contentService.queryThumbs(ip,content1.getId());
                            if(i>0){
                                content1.setContentThumbs(true);
                                continue;
                            }
                        }
                    }
                }
            }

        }
        return TableDataInfo.getDataTable(result);
    }

    /**
     * 查询用户需要审核的新闻  管理员负责把新闻退给该账号进行审核
     * @param content
     * @param request
     * @return
     */
    @PostMapping("/queryTransferApprovalPage")
    public TableDataInfo queryTransferApprovalPage(@RequestBody Content content,HttpServletRequest request){
        List<Content> result=contentService.queryTransferApprovalPage(content);
        if(StringUtils.isNotEmpty(content.getColumnId())){
            Column column=columnService.queryOne(content.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    for(Content content1:result){
                        content1.setContentThumbs(false);
                        for(String ip:ipList){
                            int i=contentService.queryThumbs(ip,content1.getId());
                            if(i>0){
                                content1.setContentThumbs(true);
                                continue;
                            }
                        }
                    }
                }
            }

        }
        return TableDataInfo.getDataTable(result);
    }
    public boolean checkColumnPermission(String id,HttpServletRequest request){
        // 获得新闻内容
        Content content = contentService.queryOne(id);
        // 获得ip地址
        String ipAddress = IpAddressUtil.getIpAddr(request);
        // 查看该ip对应该栏目的白名单情况
        if(StringUtils.isNotEmpty(ipAddress)){
            if(ipAddress.contains(",")){
                String[] split = ipAddress.split(",");
                for(String ip:split){
                    boolean b = ipService.queryIsFilterColumn(ip,content.getColumnId());
                    if(b){
                        return true;
                    }
                }
            }else{
                // 查看该栏目是否是在白名单中  如果不在直接限制访问
                return ipService.queryIsFilterColumn(ipAddress,content.getColumnId());
            }
        }
        return false;
    }
    public boolean checkIp(String id,HttpServletRequest request){
        String ipAddress = IpAddressUtil.getIpAddr(request);
        Set<String> columnIdSet=new HashSet<>();
        if(StringUtils.isNotEmpty(ipAddress)){
            if(ipAddress.contains(",")){
                String[] split = ipAddress.split(",");
                for(String ip:split){
                    Set<String> result= ipService.queryFilterColumn(ip.trim());
                    columnIdSet.addAll(result);
                }
            }else{
                ipService.addStatisticalIpNum(ipAddress.trim());
                Set<String> result= ipService.queryFilterColumn(ipAddress.trim());
                columnIdSet.addAll(result);
            }
        }
        if(columnIdSet.size()>0){
            Content result=contentService.queryOne(id);
            if(columnIdSet.contains(result.getColumnId())){
                return false;
            }
        }
        return true;
    }

    /**
     * 查询单个内容 网站需要授权的IP才可以进行访问
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/queryOne")
    public Result queryOne(String id,HttpServletRequest request){
        // 服务器地址 可以访问一切资源 59.198.2.188  127.0.0.1
        // System.out.println("访问系统IP是："+IpAddressUtil.getIpAddr(request));
        if(! "59.198.2.188".equals(IpAddressUtil.getIpAddr(request)) && ! "127.0.0.1".equals(IpAddressUtil.getIpAddr(request))){
            if(! checkColumnPermission(id,request)){ // 没有权限
                return ResultUtil.error(-1,"暂无访问权限，请联系管理员！");
            }
        }
        return queryContentById(id,request);
    }

    /**
     * 管理端专用查询单个内容
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/queryOneByManager")
    public Result queryOneByManager(String id,HttpServletRequest request){
        return queryContentByIdByManager(id,request);
    }
    public Result queryContentByIdByManager(String id,HttpServletRequest request){
        Content result=contentService.queryOne(id);
        if(StringUtils.isNotEmpty(result.getColumnId())){
            Column column=columnService.queryOne(result.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    result.setContentThumbs(false);
                    for(String ip:ipList){
                        int i=contentService.queryThumbs(ip,result.getId());
                        if(i>0){
                            result.setContentThumbs(true);
                            continue;
                        }
                    }
                }
            }

        }
        contentMapper.thumbs(id);
        return ResultUtil.success(result);
    }
    public Result queryContentById(String id,HttpServletRequest request){
         /* if(!checkIp(id,request)){
            return ResultUtil.error(-1,"暂无访问权限，请联系管理员！");
        }*/
        Content result=contentService.queryOne(id);
        if(ObjectUtils.isEmpty(result)){
            return ResultUtil.error(-1,"该新闻不存在，请稍后访问！");
        }else if("0".equals(result.getApproval())){ // 访问了未审核的内容
            return ResultUtil.error(-1,"该新闻尚未审核通过，请稍后访问！");
        }
        if(StringUtils.isNotEmpty(result.getColumnId())){
            Column column=columnService.queryOne(result.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    result.setContentThumbs(false);
                    for(String ip:ipList){
                        int i=contentService.queryThumbs(ip,result.getId());
                        if(i>0){
                            result.setContentThumbs(true);
                            continue;
                        }
                    }
                }
            }

        }
        contentMapper.thumbs(id);
        return ResultUtil.success(result);
    }
    @GetMapping("/turnPages")
    public Result turnPages(String id,String columnId){
        Map<String,Content> result=contentService.turnPages(id,columnId);
        return ResultUtil.success(result);
    }
    @GetMapping("/top")
    public Result top(String id,String type){
        int result=contentService.top(id,type);
        return ResultUtil.success(result);
    }
    @GetMapping("/nice")
    public Result nice(String id,String type){
        int result=contentService.nice(id,type);
        return ResultUtil.success(result);
    }
    @GetMapping("/statistics")
    public Result statistics(String yearAndMonth){
        List<Map<String,Object>> result=contentService.statistics(yearAndMonth);
        return ResultUtil.success(result);
    }
    @GetMapping("/queryCascadeContentGroupByColumnId")
    public Result queryCascadeContentGroupByColumnId(String id){
        List<Map<String,Object>> result=contentService.queryCascadeContentGroupByColumnId(id);
        return ResultUtil.success(result);
    }
    @PostMapping("/queryFourData")
    public Result queryFourData(@RequestBody Content content,HttpServletRequest request){
        List<Content> result=contentService.queryFourData(content);
        if(StringUtils.isNotEmpty(content.getColumnId())){
            Column column=columnService.queryOne(content.getColumnId());
            if("video".equals(column.getType())){
                String ipAddress = IpAddressUtil.getIpAddr(request);
                if(StringUtils.isNotEmpty(ipAddress)){
                    List<String> ipList=new ArrayList<>();
                    if(ipAddress.contains(",")){
                        String[] split = ipAddress.split(",");
                        for(String ip:split){
                            ipList.add(ip.trim());
                        }
                    }else{
                        ipList.add(ipAddress.trim());
                    }
                    for(Content content1:result){
                        content1.setContentThumbs(false);
                        for(String ip:ipList){
                            int i=contentService.queryThumbs(ip,content1.getId());
                            if(i>0){
                                content1.setContentThumbs(true);
                                continue;
                            }
                        }
                    }
                }
            }

        }
        return ResultUtil.success(result);
    }
    /**
     * 查询前4条数据
     * @param columnId
     * @return
     */
    @GetMapping("/queryGroupByOrg")
    public Result queryGroupByOrg(String columnId){
        List<Map<String,Object>> result=contentService.queryGroupByOrg(columnId);
        return ResultUtil.success(result);
    }
    @GetMapping("/contentThumbs")
    public Result contentThumbs(String id, HttpServletRequest request){
        String ipAddress = IpAddressUtil.getIpAddr(request);
        if(StringUtils.isNotEmpty(ipAddress)){
            List<String> ipList=new ArrayList<>();
            if(ipAddress.contains(",")){
                String[] split = ipAddress.split(",");
                for(String ip:split){
                    ipList.add(ip.trim());
                }
            }else{
                ipList.add(ipAddress.trim());
            }
            for(String ip:ipList){
                int i=contentService.queryThumbs(ip,id);
                if(i==0){
                    contentService.addThumbs(ip,id);
                }
            }
            return ResultUtil.success();

        }else{
            return ResultUtil.success();
        }

    }
    @GetMapping("/statistics1")
    public Result statistics1(String year){
        List<Map<String,Object>> result=contentService.statistics1(year);
        return ResultUtil.success(result);
    }
    @GetMapping("/statistics2")
    public Result statistics2(String year){
        List<Map<String,Object>> result=contentService.statistics2(year);
        return ResultUtil.success(result);
    }

    /**
     * 上稿率查询
     * @param year
     * @return
     */
    @GetMapping("/statistics3")
    public Result statistics3(String year){
        List<Map<String,Object>> result=contentService.statistics3(year);
        return ResultUtil.success(result);
    }

    /**
     * 大队投稿统计
     * @param year
     * @return
     */
    @GetMapping("/statistics4")
    public Result statistics4(String year){
        Map<String,Object> result=new HashMap<>();
        // 查询全部新闻
        List<Map<String,Object>> result1=contentService.statistics1(year);
        // 查询已通过的新闻
        List<Map<String,Object>> result2=contentService.statistics2(year);
        result.put("statistics1",result1);
        result.put("statistics2",result2);
        return ResultUtil.success(result);
    }

    /**
     * 投稿达人榜
     * @param year
     * @return
     */
    @GetMapping("/statistics5")
    public Result statistics5(String year){
        List<Map<String,Object>> result=contentService.statistics5(year);
        return ResultUtil.success(result);
    }
    @GetMapping("/mainBanner")
    public Result mainBanner(){
        List<Map<String,Object>> result=contentService.mainBanner();
        return ResultUtil.success(result);
    }
    @GetMapping("/getApprovalAuthByOrgId")
    public Result getApprovalAuthByOrgId(String orgId){
        if(null==orgId){
            return ResultUtil.error(-1,"参数错误");
        }
        List<Column> columns=new ArrayList<>();
        List<String> columnIdList=contentService.getApprovalAuthByOrgId(orgId);
        if(null!=columnIdList&&columnIdList.size()>0){
            for(String id:columnIdList){
                Column column = columnService.queryOne(id);
                columns.add(column);
            }

        }
        return ResultUtil.success(columns);
    }
    @PostMapping("/saveApprovalAuthByOrgId")
    public Result saveApprovalAuthByOrgId(@RequestBody Map<String,Object> param){
        if(null==param.get("orgId")||null==param.get("columnIdList")){
            return ResultUtil.error(-1,"参数错误");
        }
        String orgId=param.get("orgId").toString();
        List<String> columnIdList=(List<String>)param.get("columnIdList");
        contentService.saveApprovalAuthByOrgId(orgId,columnIdList);
        return ResultUtil.success();
    }
}